//
//  LBReactBridge+Util.h
//  LBReact
//
//  Created by WuShiHai on 19/6/19.
//  Copyright (c) 2019 Lebbay. All rights reserved.
//

#import "LBReactBridge+Util.h"

#import <LBFoundation/LBFoundation.h>

@implementation LBReactBridge(Util)

#pragma mark - Folder Operation
+ (BOOL)copyAssetFolder:(NSString *)folderPath to:(NSString *)destFolder {
    NSError *error = nil;
    [self mergeContentsOfPath:[folderPath stringByAppendingPathComponent:@"assets"]
                           to:[destFolder stringByAppendingPathComponent:@"assets"]
                        error:&error];
    return error == nil;
}

+ (BOOL)copyFolder:(NSString *)folderPath to:(NSString *)destFolder {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    [fileManager copyItemAtPath:folderPath toPath:destFolder error:&error];
    return error == nil;
}

+ (BOOL)copyFile:(NSString *)filePath to:(NSString *)destPath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    [fileManager copyItemAtPath:filePath toPath:destPath error:&error];
    return error == nil;
}

+ (void)mergeContentsOfPath:(NSString *)folderPath to:(NSString *)destFolder error:(NSError**)err {
    
    NSLog(@"- mergeContentsOfPath: %@\n intoPath: %@", folderPath, destFolder);
    
    NSFileManager *fm = [NSFileManager defaultManager];
    NSDirectoryEnumerator *srcDirEnum = [fm enumeratorAtPath:folderPath];
    NSString *subPath;
    while ((subPath = [srcDirEnum nextObject])) {
        
        NSLog(@" subPath: %@", subPath);
        NSString *srcFullPath =  [folderPath stringByAppendingPathComponent:subPath];
        NSString *potentialDstPath = [destFolder stringByAppendingPathComponent:subPath];
        
        // Need to also check if file exists because if it doesn't, value of `isDirectory` is undefined.
        BOOL isDirectory = ([[NSFileManager defaultManager] fileExistsAtPath:srcFullPath isDirectory:&isDirectory] && isDirectory);
        
        // Create directory, or delete existing file and move file to destination
        if (isDirectory) {
            NSLog(@"   create directory");
            [fm createDirectoryAtPath:potentialDstPath withIntermediateDirectories:YES attributes:nil error:err];
            if (err && *err) {
                NSLog(@"ERROR: %@", *err);
                return;
            }
        } else {
            if ([fm fileExistsAtPath:potentialDstPath]) {
                NSLog(@"   removeItemAtPath");
                [fm removeItemAtPath:potentialDstPath error:err];
                if (err && *err) {
                    NSLog(@"ERROR: %@", *err);
                    return;
                }
            }
            
            NSLog(@"   moveItemAtPath");
            [fm copyItemAtPath:srcFullPath toPath:potentialDstPath error:err];
            if (err && *err) {
                NSLog(@"ERROR: %@", *err);
                return;
            }
        }
    }
}

+ (BOOL)removeFolder:(NSString *)folderPath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    if ([fileManager fileExistsAtPath:folderPath isDirectory:nil]) {
       [fileManager removeItemAtPath:folderPath error:&error];
        return error == nil;
    }
    return YES;
}

+ (BOOL)inspectFolderPath:(NSString *)folderPath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:folderPath isDirectory:&isDir];
    if (!(isDir == YES && existed == YES)) {
        // 在 Document 目录下创建一个 head 目录
        NSError *error = nil;
        [fileManager createDirectoryAtPath:folderPath
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:&error];
        return error == nil;
    }
    return isDir && existed;
}

+ (NSString *)executePathForResource:(NSString *)name withExtension:(NSString *)extension {
    NSString *folderName = [[NSString stringWithFormat:@"%@%@%@%@.%@",
                             AppBundleIdentifier(),
                             AppBuildVersionNumber(),
                             AppReleaseVersionNumber(),name, extension] MD5];
    NSString *filePath = [[[[self executeRootPath] stringByAppendingPathComponent:folderName] stringByAppendingPathComponent:name] stringByAppendingPathExtension:extension];
    return filePath;
}

+ (NSString *)executePathFor:(NSString *)folderPath {
    NSString *folder = [[self executeRootPath] stringByAppendingPathComponent:[folderPath MD5]];
    return folder;
}

+ (NSString *)executeRootPath {
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    return [docPath stringByAppendingPathComponent:@"react/execute"];
}

+ (NSString *)pathOfJSBundleIn:(NSString *)folderPath {
    NSFileManager *manager = [NSFileManager defaultManager];
    //1.获取文件夹下所有的子路径
    NSArray *allPath =[manager subpathsAtPath:folderPath];
    
    __block NSString *localPathOfBundle = nil;
    //2.遍历所有的子路径
    __weak __typeof(&*self) weakSelf = self;
    [allPath enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([obj hasSuffix:@"bundle"]) {
            localPathOfBundle = [folderPath stringByAppendingPathComponent:obj];
            *stop = YES;
        }
    }];
    return localPathOfBundle;
}

@end
